package com.oncecloud.devops.client.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.oncecloud.devops.client.constant.Status;
import com.oncecloud.devops.client.entity.Authority;
import com.oncecloud.devops.client.entity.Env;
import com.oncecloud.devops.client.entity.User;
import com.oncecloud.devops.client.ldap.LdapAnon;
import com.oncecloud.devops.client.model.LoginModel;
import com.oncecloud.devops.client.service.AuthorityService;
import com.oncecloud.devops.client.service.ProjectService;
import com.oncecloud.devops.client.service.UserService;
import com.oncecloud.devops.client.util.HashUtil;
import com.oncecloud.devops.client.util.LoginUserCache;
import com.oncecloud.devops.client.util.Result;

/**
 * @author xzg
 *
 */
@Controller
public class LoginEnvController {
	private static final Logger LOGGER = Logger.getLogger(LoginEnvController.class);
	@Resource
	private UserService userService;
	@Resource
	private LdapAnon ldapAnon;
	@Resource
	private AuthorityService authorityService;
	@Resource
	private ProjectService projectservice;
	
	@RequestMapping(value="/login.do",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Result login(HttpServletRequest request, HttpServletResponse response, LoginModel loginRequestModel,
			RedirectAttributes redirectAttributes) {
		LOGGER.info("【" + loginRequestModel.getUserName() + "】尝试登录");
		User user=new User();
		Result result = new Result();
		//默认信息为失败
		int iResult = ldapAnon.authenricate(loginRequestModel.getUserName(), loginRequestModel.getPassword());
		
		if (iResult < 0 || (iResult != 0 && iResult!=1) ) {
			result.setMessage("账号或密码错误！");
			result.setSuccess(false);
			return result;
		}
		//根据用户ID获取用户信息 
		try {
			user = userService.getUserByUid(loginRequestModel.getUserName());
		} catch (Exception e) {
			LOGGER.error("check user login by userName["+loginRequestModel.getUserName()+"] falied!", e);
			result.setMessage("用户登录失败，数据库连接异常！");
			result.setSuccess(false);
			return result;
		}
		//用户不存在
		if (user == null) {
			LOGGER.error("用户不存在！");
			result.setMessage("用户不存在！");
			result.setSuccess(false);
			return result;
		}
		//用户密码错误
		if(user != null && !StringUtils.hasText(user.getUserPass())){
			LOGGER.error("用户密码错误！");
			result.setMessage("用户密码错误");
			result.setSuccess(false);
			return result;
		}
		//如果ldap认证通过（1 == iResult），数据库密码和ldap密码不一致,则更新数据库密码  1 == iResult &&
		if( !HashUtil.md5Hash(loginRequestModel.getPassword()).equals(user.getUserPass())) {
		    user.setUserPass(HashUtil.md5Hash(loginRequestModel.getPassword()));
		    try {
				userService.updateUserByUserId(user);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				LOGGER.error("用户信息更新失败！");
				e.printStackTrace();
			}
		//如果未开启ldap认证，需要判断用户密码是否与数据库一致
		}else if(!HashUtil.md5Hash(loginRequestModel.getPassword()).equals(user.getUserPass())){
			result.setMessage("用户密码错误");
			result.setSuccess(false);
			return result;
		}
		//用户被冻结
		if(user != null && user.getUserStatus() == Status.USER.FROZEN.ordinal()){
			LOGGER.warn("登录失败：该用户已被冻结！");
			result.setMessage("该用户已被冻结,请联系管理员！");
			result.setSuccess(false);
			return result;
		}
		//用户账号已作废
		if(user != null && user.getUserStatus() == Status.USER.DELETE.ordinal()){
			LOGGER.warn("登录失败：该用户账号已作废！");
			result.setMessage("该用户账号已作废,请联系管理员！");
			result.setSuccess(false);
			return result;
		}
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";
		/*
		//获取用户第一个一级菜单权限
		String startPage=new String();
		boolean startFlag=true;
		//【三】：获取用户权限信息，存储在session中
		List<String> authlist=new ArrayList<String>();
		List<Authority> listAuths = authorityService.getUserRoleAuths(user.getUserId());
		if(listAuths.size()==0){
			LOGGER.warn("登录失败：用户没有相关权限！");
			redirectAttributes.addFlashAttribute("message", "用户没有相关权限！");
			return new ModelAndView(new RedirectView("/login.html"));
		}
		//pages： 一级菜单权限、  buttons：二级按钮权限
		String pages = "";
		String buttons = "";
		for(Authority ahr:listAuths){
			if(ahr.getAuthorityRelativeUrl()!=null){
				authlist.add(ahr.getAuthorityRelativeUrl());
			}
			if(ahr.getAuthorityType() == Status.AUTHTYPE.PAGE.ordinal()){
				pages += ahr.getAuthorityRemarks()+",";
				if(startFlag&&ahr.getAuthorityRelativeUrl()!=null){
					startPage=ahr.getAuthorityRelativeUrl();
					startFlag=false;
				}
			}else if(ahr.getAuthorityType() == Status.AUTHTYPE.BUTTON.ordinal()){
				buttons += ahr.getAuthorityRemarks()+",";
			}
		}*/
		//用户登录成功，设置用户状态为登录状态()
		try {
			user.setUserLogingSessionId(request.getSession().getId());
			user.setLoginStatus((byte) 1);
			userService.updateUserByUserId(user);
		} catch (Exception e) {
			LOGGER.error("get user by username["+loginRequestModel.getUserName()+"] falied!", e);
			result.setMessage("用户登录失败，数据库连接异常！");
			result.setSuccess(false);
			return result;
		}
		
		/*//权限存储到session中（pagesAuth、buttonsAuth控制界面的权限显示效果，authlist 权限url过滤）
		request.getSession().setAttribute("pagesAuth", pages);
		request.getSession().setAttribute("buttonsAuth", buttons);
		//保存了该角色可用url
		//request.getSession().setAttribute("authlist", authlist);
		request.getSession().setAttribute("listAuths", listAuths);
		//request.getSession().setAttribute("userTenantId", user.getTenantId());
		 * */
		//用户信息和项目url存储在session中
		request.getSession().setAttribute("user", user);
		request.getSession().setAttribute("basePath", basePath);
		
		LoginUserCache.USER_ID = user.getUserId();
		LOGGER.info(loginRequestModel.getUserName() + "登录成功");
		
		//返回对应的环境列表以供选择
		List<Env> list = userService.getEnv(user);
		if(0==list.size()){
			result.setMessage("该用户不存在相应的环境");
			result.setSuccess(false);
			return result;
		}
		result.setMessage("登录成功!");
		result.setSuccess(true);
		result.setData(list);
		return result;
	}
	
	@RequestMapping(value="/getUrl.do",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Result getUrl(HttpServletRequest request,@RequestParam("envId") Integer envId){
		Result result = new Result();
		User user = null;
		Map<String,Integer> map = new HashMap<String,Integer>();
		HttpSession session = request.getSession();
		 user = (User) session.getAttribute("user");
		if(null == user){
			result.setMessage("会话信息失效！");
			result.setSuccess(false);
			return result;
		}
		//首先取得用户默认的环境ID
		Integer envermentId = null == envId? user.getDefaultEnvId():envId;
		if(null == envermentId){
			result.setMessage("该用户无可用环境请与管理员联系");
			result.setSuccess(false);
			return result;
		}
		map.put("userId", user.getUserId());
		map.put("envId",envermentId);
		List<Authority>	list =  authorityService.getUserRoleAuths(map);
		if(null == list|| 0 == list.size()){
			result.setMessage("该用户还没有相应的权限，请联系上级管理员！！");
			result.setSuccess(false);
			return result;
		}
		//正常
		result.setMessage("权限列表查询成功");
		result.setSuccess(true);
		result.setData(list);
		return result;
	}
}
